package com.soc.file.controller;



import com.soc.file.bean.Result;
import lombok.SneakyThrows;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class BaseFileController {

    @SneakyThrows
    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new Result(500,"文件为空",file) ;
        }
//
        // 获取上传文件的文件名
        String fileName = file.getOriginalFilename();
        // 获取上传文件的文件扩展名
        String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
        // 重新生成唯一的文件名
        String newFileName = UUID.randomUUID().toString() + "." + fileExtension;
        // 设置文件存储路径
        String filePath = "/data/uploaf/file/" + newFileName;
        String url = "/api/file/" +newFileName;

        byte[] bytes = filePath.getBytes("UTF-8");
        try {
            // 保存文件1
            file.transferTo(new File(filePath));
//            R.ok("上传成功",url)
            return new Result(200,"成功",url) ;
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(500,"上传失败",000);
        }
    }

    @GetMapping("/fileNames")
    public List<String> getFileNames() {
        String path = "/data/uploaf/file/"; // 指定文件路径
        File[] files = new File(path).listFiles();
        List<String> fileNames = new ArrayList<>();

        for (File file : files) {
            if (file.isFile()) {
                fileNames.add(file.getName()); // 添加文件名到列表中
            }
        }

        return fileNames;
    }

///data/uploaf/file/
    @DeleteMapping("/deleteFile")
    public boolean deleteFile(@RequestParam("fileName") String fileName) {
        String filepath = "/data/uploaf/file/" + fileName; // 指定文件路径及文件名
        File file = new File(filepath);
        if (file.exists() && file.isFile()) {
            return file.delete();
        } else {
            return false;
        }
    }




//         文件访问路径，需要根据具体情况调整
        private final String filePath = "/data/uploaf/file/";
        @GetMapping("/{filename}")
        public ResponseEntity<Resource> downloadFile(@PathVariable  String filename) throws MalformedURLException, UnsupportedEncodingException {
            File file = new File(filePath+ filename);
            Resource resource = new UrlResource(file.toURI().toURL());
            String fileNameEncoder = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
            System.out.println(filename+"===>"+fileNameEncoder);
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" +fileNameEncoder)
                    .body(resource);

        }




}
